package com.lefu.es.util;

import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.lefu.es.application.IwellnessApplication;
import com.lefu.es.constant.UtilConstants;
import com.lefu.es.entity.FitBitPostBo;
import com.lefu.es.entity.FitBitResponseBo;
import com.lefu.es.entity.Records;
import com.lefu.es.event.RevokeFitbit;
import com.lefu.es.service.RecordService;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.Map;

/**fit bit帮助类
 * Created by andychen83 on 2017/11/4.
 */

public class FitbitHelper {

    private OkManager manager;
    private static String TAG ="FitbitHelper";
    private volatile static FitbitHelper fitbitHelper;   //防止多个线程访问时

    private Handler handler;

    RecordService recordService;


    private FitbitHelper() {
        handler = new Handler(Looper.getMainLooper());
    }

    //采用单例模式获取对象
    public static FitbitHelper getInstance() {
        if(null== UtilConstants.su){
            UtilConstants.su = new SharedPreferencesUtil(IwellnessApplication.app);
        }
        if (fitbitHelper == null) {
            synchronized (FitbitHelper.class) {                //同步代码块
                    fitbitHelper = new FitbitHelper();
                }
            }
        return fitbitHelper;
    }

    public String getPostWeightUrl(String userId){
        return "https://api.fitbit.com/1/user/"+userId+"/body/log/weight.json";
    }


    public String getPostghFatUrl(String userId){
        return "https://api.fitbit.com/1/user/"+userId+"/body/log/fat.json";
    }

    public String getRevokeTokenUrl(String token){
        return "https://api.fitbit.com/oauth2/revoke?token="+token;
    }

/*
    */
/**
     * 数据同步
     *//*

    public void syncFitbitDatas(){
        if(null==recordService)recordService= new RecordService(IwellnessApplication.app);
        try {
            List<Records> ls = recordService.findNoSendToFitbitRes();
            if(null!=ls && ls.size()>0){
                for (Records record:ls) {
                    Thread.sleep(3000);
                    FitbitHelper.getInstance().postWeightAndFatData(record);
                }
            }
        } catch (Exception e) {
            Log.e("FitbitH", "run: fitbit数据同步异常" );
        }
    }
*/


    public void postWeightAndFatData(Records records){
        LogUtils.d(TAG,"=======上传数据到fitbit:"+records);
        new PostWeightDataTask().execute(records);
    }

    public void revokeToken(){
        new RevokeFibitDataTask().execute();
    }
    /**
     * 发送 体重数据
     */
    class PostWeightDataTask extends AsyncTask<Records, Integer, Records> {

        @Override
        protected Records doInBackground(Records... params) {
            try {
                LogUtils.d(TAG,"发送体重数据到服fitbit");
                Records records = null;
                if(null==manager){
                    manager = OkManager.getInstance();
                }
                Map<String, String> map = null;
//                if(null==params[0]){
//                    return "传过来的记录参数为空";
//                }
//                if( !params[0].getUgroup().equals("P0")  ){
//                    return "用户组不为P0";
//                }
//                if( TextUtils.isEmpty(params[0].getRecordTime())){
//                    return "测量时间为空";
//                }
                if(null!=params[0] && params[0].getUgroup().equals("P1") && !TextUtils.isEmpty(params[0].getRecordTime())){
                    map = new HashMap<String, String>();
                    map.put("weight", UtilTooth.keep2Point(params[0].getRweight()));
                    map.put("date", DateUtil.formatDate(UtilTooth.stringToTime(params[0].getRecordTime())));
                    map.put("time",  DateUtil.formatTime(UtilTooth.stringToTime(params[0].getRecordTime())));
                }
                if(null==map)return null;
                UtilConstants.FIBIT_USER_ID_VALUE = (String) UtilConstants.su.readbackUp("lefuconfig", UtilConstants.FIBIT_USER_ID_KEY, "");
                UtilConstants.FIBIT_ACCESS_TOKEN_VALUE = (String) UtilConstants.su.readbackUp("lefuconfig", UtilConstants.FIBIT_ACCESS_TOKEN_KEY, "");
                if(TextUtils.isEmpty(UtilConstants.FIBIT_USER_ID_VALUE ) || TextUtils.isEmpty(UtilConstants.FIBIT_ACCESS_TOKEN_VALUE )){
                    return null;
                }
                String url = FitbitHelper.getInstance().getPostWeightUrl(UtilConstants.FIBIT_USER_ID_VALUE);
                String res= manager.sentDataByPost(url,map, UtilConstants.FIBIT_ACCESS_TOKEN_VALUE);
                //更新数据库数据
                if(!TextUtils.isEmpty(res)){
                    if("401".equals(res)){//未授权
                        UtilConstants.su.editSharedPreferences("lefuconfig", UtilConstants.FIBIT_ACCESS_TOKEN_KEY, "");
                        UtilConstants.su.editSharedPreferences("lefuconfig", UtilConstants.FIBIT_USER_ID_KEY, "");
                        UtilConstants.FIBIT_IS_OPEN = 0;
                    }else{
                        //{"weightLog":{"bmi":24.05,"date":"2017-11-03","logId":1509719410000,"source":"api","time":"14:30:10","weight":69.5}}
                        //更新数据库
                        FitBitResponseBo rescords =  JSON.parseObject(res,FitBitResponseBo.class);
                        if(null!=rescords && !TextUtils.isEmpty(rescords.getWeightLog())){
                            FitBitPostBo postBo =  JSON.parseObject(rescords.getWeightLog(),FitBitPostBo.class);
                            if(null==recordService)recordService = new RecordService(IwellnessApplication.app);
                            params[0].setFitbitId(postBo.getLogId());
                            params[0].setSyncFitbit("1");
                            recordService.updateByTime(params[0]);
                        }
                        records = params[0];
                    }
                }else{
                    records = new Records();
                    records.setUgroup(res);
                }

                return records;
            }catch (Exception e){
                e.printStackTrace();
                return null;
            }

       }
        @Override
        protected void onPostExecute(Records s) {
            super.onPostExecute(s);
            //ToastUtils.ToastCenter(IwellnessApplication.app,"发送完成,fitbit返回数据==》"+s);
            if(null!=s){
                if(s.getRweight()>0){
                    //ToastUtils.ToastCenter(IwellnessApplication.app,"发送成功"+JSON.toJSONString(s));
                    new PostFatDataTask().execute(s);
                }else{
                    //ToastUtils.ToastCenter(IwellnessApplication.app,"发送失败"+s.getUgroup());
                }
            }else{
               // ToastUtils.ToastCenter(IwellnessApplication.app,"发送失败==》");
            }
        }
    }

    /**
     * 发送 脂肪数据
     */
    class PostFatDataTask extends AsyncTask<Records, Integer, Records> {


        @Override
        protected Records doInBackground(Records... params) {
            Records records = null;
            try {
                if(null==manager){
                    manager = OkManager.getInstance();
                }
                Map<String, String> map = null;
                if(null!=params[0] && !TextUtils.isEmpty(params[0].getRecordTime())){
                    map = new HashMap<String, String>();
                    map.put("fat", UtilTooth.keep2Point(params[0].getRbodyfat()));
                    map.put("date", DateUtil.formatDate(UtilTooth.stringToTime(params[0].getRecordTime())));
                    map.put("time",  DateUtil.formatTime(UtilTooth.stringToTime(params[0].getRecordTime())));
                }
                if(null==map)return null;
                UtilConstants.FIBIT_USER_ID_VALUE = (String) UtilConstants.su.readbackUp("lefuconfig", UtilConstants.FIBIT_USER_ID_KEY, "");
                UtilConstants.FIBIT_ACCESS_TOKEN_VALUE = (String) UtilConstants.su.readbackUp("lefuconfig", UtilConstants.FIBIT_ACCESS_TOKEN_KEY, "");
                if(TextUtils.isEmpty(UtilConstants.FIBIT_USER_ID_VALUE ) || TextUtils.isEmpty(UtilConstants.FIBIT_ACCESS_TOKEN_VALUE )){
                    return null;
                }
                String url = FitbitHelper.getInstance().getPostghFatUrl(UtilConstants.FIBIT_USER_ID_VALUE);
                String res= manager.sentDataByPost(url,map, UtilConstants.FIBIT_ACCESS_TOKEN_VALUE);
                //更新数据库数据
                if(!TextUtils.isEmpty(res)){
                    if("401".equals(res)){//未授权
                        UtilConstants.su.editSharedPreferences("lefuconfig", UtilConstants.FIBIT_ACCESS_TOKEN_KEY, "");
                        UtilConstants.su.editSharedPreferences("lefuconfig", UtilConstants.FIBIT_USER_ID_KEY, "");
                    }else{
                        //{"weightLog":{"bmi":24.05,"date":"2017-11-03","logId":1509719410000,"source":"api","time":"14:30:10","weight":69.5}}
                        //更新数据库
                        FitBitResponseBo rescords =  JSON.parseObject(res,FitBitResponseBo.class);
                        if(null!=rescords && !TextUtils.isEmpty(rescords.getWeightLog())){
                            FitBitPostBo postBo =  JSON.parseObject(rescords.getWeightLog(),FitBitPostBo.class);
                            if(null==recordService)recordService = new RecordService(IwellnessApplication.app);
                            params[0].setFitbitId(postBo.getLogId());
                            params[0].setSyncFitbit("2");
                            recordService.update(params[0]);
                        }
                        records = params[0];
                    }
                }

                return records;
            }catch (Exception e){
                return null;
            }
        }


    }


    /**
     * 撤销授权
     */
    class RevokeFibitDataTask extends AsyncTask<String, Integer, String> {


        @Override
        protected String doInBackground(String... params) {
            try {
                if(null==manager){
                    manager = OkManager.getInstance();
                }
                UtilConstants.FIBIT_USER_ID_VALUE = (String) UtilConstants.su.readbackUp("lefuconfig", UtilConstants.FIBIT_USER_ID_KEY, "");
                UtilConstants.FIBIT_ACCESS_TOKEN_VALUE = (String) UtilConstants.su.readbackUp("lefuconfig", UtilConstants.FIBIT_ACCESS_TOKEN_KEY, "");
                if(TextUtils.isEmpty(UtilConstants.FIBIT_USER_ID_VALUE ) || TextUtils.isEmpty(UtilConstants.FIBIT_ACCESS_TOKEN_VALUE )){
                    return null;
                }

                String str2  = UtilConstants.ClientID+":"+ UtilConstants.ClientSecret;

                String base64Encoded3 = Base64Encoder.encode( str2.getBytes("UTF-8"));
                String url = FitbitHelper.getInstance().getRevokeTokenUrl(UtilConstants.FIBIT_ACCESS_TOKEN_VALUE);


                String res= manager.sentRevokeByPost(url, UtilConstants.FIBIT_ACCESS_TOKEN_VALUE,base64Encoded3);

                //更新数据库数据

                return res;
            }catch (Exception e){
                return null;
            }
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if(TextUtils.isEmpty(s)){
                EventBus.getDefault().post(new RevokeFitbit(true));
            }else{
                if(!s.startsWith("40")){
                    UtilConstants.su.editSharedPreferences("lefuconfig", UtilConstants.FIBIT_USER_ID_KEY, "");
                    UtilConstants.su.editSharedPreferences("lefuconfig", UtilConstants.FIBIT_ACCESS_TOKEN_KEY, "");
                    UtilConstants.FIBIT_USER_ID_VALUE = "";
                    UtilConstants.FIBIT_ACCESS_TOKEN_VALUE =  "";
                    UtilConstants.FIBIT_IS_OPEN=0;
                    EventBus.getDefault().post(new RevokeFitbit(true));
                }else{
                    EventBus.getDefault().post(new RevokeFitbit(false));
                }
            }

        }
    }

}
